package com.gitee.wsl.func.procedure.sample

import com.gitee.wsl.base.Option
import com.gitee.wsl.base.empty
import com.gitee.wsl.base.ofNullable
import com.gitee.wsl.func.procedure.Procedure


/**
 * Implementation of [Procedure] that holds on to the minimum element seen so far,
 * determined by the [Function].
 */
class MinProcedure<T> : Procedure<T> {
    protected var visitedAtLeastOnce: Boolean = false
    var result: T? = null
        get() {
            if (!this.visitedAtLeastOnce) {
                throw NoSuchElementException()
            }
            return field
        }

//    fun getResult(): T? {
//        if (!this.visitedAtLeastOnce) {
//            throw NoSuchElementException()
//        }
//        return this.result
//    }

    val resultOptional: Option<T>
        get() {
            if (!this.visitedAtLeastOnce) {
                return Option.empty()
            }
            return Option.ofNullable(this.result)
        }

    override fun value(each: T) {
        if (this.visitedAtLeastOnce) {
            if ((each as Comparable<T?>) < this.result) {
                this.result = each
            }
        } else {
            this.visitedAtLeastOnce = true
            this.result = each
        }
    }

}
